package com.ft.oa.service.development.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ft.oa.domain.development.DevNeed;
import com.ft.oa.domain.development.DevNeedIssue;
import com.ft.oa.domain.development.NeedAnalyse;
import com.ft.oa.domain.development.NeedContract;
import com.ft.oa.domain.dto.ApiResult;
import com.ft.oa.domain.dto.knowledgeBase.AttachmentDto;
import com.ft.oa.domain.dto.sys.SecurityUser;
import com.ft.oa.domain.project.ExecProject;
import com.ft.oa.enums.DirectoryTypeEnum;
import com.ft.oa.enums.ManagerEnum;
import com.ft.oa.mapper.attachment.AttachmentMapper;
import com.ft.oa.mapper.development.DevNeedIssueMapper;
import com.ft.oa.mapper.development.DevNeedMapper;
import com.ft.oa.mapper.development.NeedContractMapper;
import com.ft.oa.mapper.industrysMapper.DevNeedAnalyseMapper;
import com.ft.oa.mapper.project.ExecProjectMapper;
import com.ft.oa.service.development.DevNeedAnalyseService;
import com.ft.oa.service.knowledgeBase.DirectoryService;
import com.ft.oa.utils.MapUtil;
import com.ft.oa.utils.SecurityUtils;
import com.ft.oa.utils.UploadFileUtile;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class DevNeedAnalyseServiceImpl implements DevNeedAnalyseService {

    @Resource
    private DevNeedMapper devNeedMapper;

    @Resource
    private DevNeedAnalyseMapper devNeedAnalyseMapper;

    @Resource
    private UploadFileUtile uploadFileUtile;

    @Resource
    private AttachmentMapper attachmentMapper;

    @Resource
    private NeedContractMapper needContractMapper;

    @Resource
    private DirectoryService directoryService;

    @Resource
    private ExecProjectMapper execProjectMapper;

    @Resource
    private DevNeedIssueMapper devNeedIssueMapper;

    /**
     * 需求分析分页已经确认的需求
     *
     * @param devNeed
     * @return
     */
    @Override
    public Page<DevNeed> page(DevNeed devNeed) {
        //两个分页 主列表分页不需要传IsAnalyse 需求分析列表需要传IsAnalyse = 1
        QueryWrapper<DevNeed> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ManagerEnum.GENERAL.toString().equals(SecurityUtils.getCurrentUser().getManager()), DevNeed::getChargePersonId,SecurityUtils.getCurrentUser().getId())
                .eq(devNeed.getCategory() != null, DevNeed::getCategory, devNeed.getCategory())
                .eq(StringUtils.isNotBlank(devNeed.getUrgencyState()), DevNeed::getUrgencyState, devNeed.getUrgencyState())
                .eq(DevNeed::getDataState, 2)
                .eq(StringUtils.isNotBlank(devNeed.getCustomerName()), DevNeed::getCustomerName, devNeed.getCustomerName())
               .eq(StringUtils.isNotBlank(devNeed.getIsAnalyse()),DevNeed::getIsAnalyse, devNeed.getIsAnalyse()).orderByDesc(DevNeed::getId);

        Page<DevNeed> page = new Page<>(devNeed.getPage(), devNeed.getSize());
        Page<DevNeed> result = devNeedMapper.selectPage(page, wrapper.orderByDesc("create_time"));
        result.getRecords()
                .forEach(
                        e -> {
                            QueryWrapper<NeedContract> contractWrapper = new QueryWrapper<>();
                            contractWrapper.lambda()
                                    .eq(NeedContract::getNeedId, e.getId())
                                    .eq(NeedContract::getDel,false);
                            List<NeedContract> needContracts = needContractMapper.selectList(contractWrapper);
                            e.setNeedContractList(needContracts);
                            /*查询产品类别*/
                            DevNeedIssue issue = devNeedIssueMapper.selectById(e.getIssueId());
                            if(issue!=null){
                                e.setProductCategory(issue.getProductCategory());
                            }

                        }
                );

        return result;
    }

    @Override
    public ApiResult addNeedAttachment(NeedAnalyse needAnalyse) {
        Long needId = needAnalyse.getNeedId();
        SecurityUser currentUser = SecurityUtils.getCurrentUser();
        needAnalyse.setSubmitId(currentUser.getId());
        needAnalyse.setSubmitUser(currentUser.getUsername());
        needAnalyse.setCreateTime(LocalDateTime.now());
        needAnalyse.setUpdateTime(LocalDateTime.now());
        needAnalyse.setState(0);
        devNeedAnalyseMapper.insert(needAnalyse);
        DevNeed devNeed = devNeedMapper.selectById(needId);
        devNeed.setIsAnalyse("1");
        devNeedMapper.updateById(devNeed);
        boolean temp = false;
        if(needAnalyse.getAttachments() != null && needAnalyse.getAttachments().size() > 0){
            String attachmentRel = JSONArray.toJSONString(needAnalyse.getAttachments());
            needAnalyse.setAttachmentRel(attachmentRel);
            ExecProject execProject = new ExecProject();
            if(devNeed.getProjectId() != null){
                execProject = execProjectMapper.selectById(devNeed.getProjectId());
                if(execProject != null && StringUtils.isNotBlank(execProject.getProjectNumber())){
                    temp = true;
                }
            }
            if(temp){
                directoryService.saveProAttachment(
                        needAnalyse.getAttachments(),
                        DirectoryTypeEnum.DEV_NEED_ANALYSE.getCode(),
                        needAnalyse.getId().toString(),
                        "1",
                        execProject.getProjectNumber()//TODO 如果为null则存projectName
                );
            }else{
                directoryService.saveProAttachment(
                        needAnalyse.getAttachments(),
                        DirectoryTypeEnum.DEV_NEED_ANALYSE.getCode(),
                        needAnalyse.getId().toString(),
                        "1",
                        devNeed.getProjectName() //TODO 如果为null则存projectName
                );
            }
        }
        devNeedAnalyseMapper.updateById(needAnalyse);
        return ApiResult.simpleSuccess();
    }

    @Override
    public Page<NeedAnalyse> needAnalysePage(Map<String, Object> params) {
        QueryWrapper<NeedAnalyse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("need_id", MapUtil.getStrValue(params, "needId"));
        queryWrapper.eq("state", 0);
        if (StringUtils.isNotEmpty(MapUtil.getStrValue(params, "docName"))) {
            queryWrapper.like("docName", MapUtil.getStrValue(params, "docName"));
        }
        Page<NeedAnalyse> page = new Page<>((int) params.get("page"), (int) params.get("size"));
        Page<NeedAnalyse> needAnalysePage = devNeedAnalyseMapper.selectPage(page, queryWrapper.orderByDesc("create_time"));
        needAnalysePage.getRecords().forEach(e->{
            String attachmentRel = e.getAttachmentRel();
            e.setAttachments(JSONObject.parseArray(attachmentRel, AttachmentDto.class));
        });
        return needAnalysePage;
    }

    @Override
    public void needAnalyseUpdate(NeedAnalyse needAnalyse) {
        LambdaUpdateChainWrapper<NeedAnalyse> wrapper = new LambdaUpdateChainWrapper<>(devNeedAnalyseMapper);
        if(needAnalyse.getAttachments() != null && needAnalyse.getAttachments().size() > 0){
            DevNeed devNeed = devNeedMapper.selectById(needAnalyse.getNeedId());
            boolean temp = false;
            String attachmentRel = JSONArray.toJSONString(needAnalyse.getAttachments());
            needAnalyse.setAttachmentRel(attachmentRel);
            ExecProject execProject = new ExecProject();
            if(devNeed.getProjectId() != null){
                execProject = execProjectMapper.selectById(devNeed.getProjectId());
                if(execProject != null && StringUtils.isNotBlank(execProject.getProjectNumber())){
                    temp = true;
                }
            }
            if(temp){
                directoryService.saveProAttachment(
                        needAnalyse.getAttachments(),
                        DirectoryTypeEnum.DEV_NEED_ANALYSE.getCode(),
                        needAnalyse.getId().toString(),
                        "1",
                        execProject.getProjectNumber()//TODO 如果为null则存projectName
                );
            }else{
                directoryService.saveProAttachment(
                        needAnalyse.getAttachments(),
                        DirectoryTypeEnum.DEV_NEED_ANALYSE.getCode(),
                        needAnalyse.getId().toString(),
                        "1",
                        devNeed.getProjectName() //TODO 如果为null则存projectName
                );
            }
        }
        boolean update = wrapper.eq(NeedAnalyse::getId, needAnalyse.getId())
                .set(org.springframework.util.StringUtils.hasText(needAnalyse.getDocName()), NeedAnalyse::getDocName, needAnalyse.getDocName())
                .set(org.springframework.util.StringUtils.hasText(needAnalyse.getVersion()), NeedAnalyse::getVersion, needAnalyse.getVersion())
                .set(org.springframework.util.StringUtils.hasText(needAnalyse.getDocType()), NeedAnalyse::getDocType, needAnalyse.getDocType())
                .set(org.springframework.util.StringUtils.hasText(needAnalyse.getAuthor()), NeedAnalyse::getAuthor, needAnalyse.getAuthor())
                .set(needAnalyse.getAttachmentRelId() != null, NeedAnalyse::getAttachmentRelId, needAnalyse.getAttachmentRelId())
                .set(org.springframework.util.StringUtils.hasText(needAnalyse.getRemark()), NeedAnalyse::getRemark, needAnalyse.getRemark())
                .set(NeedAnalyse::getUpdateTime, LocalDateTime.now())
                .set(StringUtils.isNotBlank(needAnalyse.getAttachmentRel()),NeedAnalyse::getAttachmentRel,needAnalyse.getAttachmentRel())
                .update();
    }

    @Override
    public void needAnalyseDelete(NeedAnalyse needAnalyse) {
        LambdaUpdateChainWrapper<NeedAnalyse> wrapper = new LambdaUpdateChainWrapper<>(devNeedAnalyseMapper);
        wrapper.eq(NeedAnalyse::getId, needAnalyse.getId())
                .set(NeedAnalyse::getState, 1)
                .set(NeedAnalyse::getDelTime,LocalDateTime.now())
                .update();
        //删除本条需求分析之后 去dev_need表查到这条关联的数据 判断这条需求下边是否还有需求分析文档 如果没有setIsAnalyse("0") 如果有的话setIsAnalyse("1");
        DevNeed devNeed = devNeedMapper.selectById(needAnalyse.getNeedId());
        devNeed.setIsAnalyse("0");
        QueryWrapper<NeedAnalyse> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(NeedAnalyse::getNeedId, needAnalyse.getNeedId());
        List<NeedAnalyse> needAnalyses = devNeedAnalyseMapper.selectList(queryWrapper);
        if (needAnalyses != null && !needAnalyses.isEmpty() ) {
            Iterator var1 = needAnalyses.iterator();
            while (var1.hasNext()) {
                NeedAnalyse next = (NeedAnalyse) var1.next();
                Integer state = next.getState();
                if (state !=null && state == 0) {//不会出现null转int的情况 经过分析的文档 state为1 如果删除 state为0
                    devNeed.setIsAnalyse("1");
                    break;
                }
            }
        }
        devNeedMapper.updateById(devNeed);
    }
}
